package string;

public class KMP {

    /**
     * 生成模式匹配数组
     * @param pattern
     * @return
     */
    public static int[] getNext(String pattern) {
        int n = pattern.length();
        int[] next = new int[n];
        next[0] = -1;
        int j = -1;
        //示例：ABCDABD
        for (int i = 1; i < n; i++) {
            //和前缀不同则后退到上一个前缀的位置，直到后退到开始或者上一个前缀匹配成功
            while (j >= 0 && pattern.charAt(j + 1) != pattern.charAt(i)) {
                j = next[j];
            }
            //和前缀相同就前进一位
            if (pattern.charAt(j + 1) == pattern.charAt(i)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    /**
     * 匹配
     * @param text
     * @param pattern
     * @return
     */
    public static int kmp(String text, String pattern) {
        int n = text.length();
        int m = pattern.length();
        int[] next = getNext(pattern);
        int j = -1;
        //主串一直前进，从不后退
        for (int i = 0; i < n; i++) {
            //有匹配成功且下一位匹配不成功，则重置pattern开始匹配状态
            while (j >= 0 && pattern.charAt(j + 1) != text.charAt(i)) {
                j = next[j];
            }
            //匹配成功前进一位
            if (pattern.charAt(j + 1) == text.charAt(i)) {
                j++;
            }
            //全部匹配成功
            if (j == m - 1) {
                return i - m + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String text = "ABCDABCDABDEABCDABD";
        String pattern = "ABCDABD";
        int index = kmp(text, pattern);
        System.out.println(index);
    }
}
